package cn.jsj.onclock.configuration;

import cn.jsj.onclock.management.ExcelWorkBookFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Excel模板读取
 *
 * @author 卢斌
 */
@Slf4j
@Configuration
public class ExcelModelInitConfiguration {

    @Value("${excel-name}")
    private String excelName;

    @Bean
    public ByteArrayOutputStream byteArrayOutputStream() {
        ClassPathResource resource = new ClassPathResource("static/" + excelName);
        log.info("获取到excel模板文件源：{}", resource.getPath());
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        log.info("字节缓存流建立");
        int len = 0;
        byte[] buffer = new byte[1024];
        try {
            inputStream = resource.getInputStream();
            log.info("开始读取Excel模板文件");
            while (len != -1) {
                len = inputStream.read(buffer);
                if (len != -1) {
                    byteArrayOutputStream.write(buffer, 0, len);
                }
            }
            log.info("Excel模板文件读取完成");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        log.info("文件输入流关闭，Excel模板缓存成功");
        return byteArrayOutputStream;
    }

}
